package com.xcenter.cabinet.file.service;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.xcenter.cabinet.file.dao.FileDao;
import com.xcenter.cabinet.file.util.FileUtils;
import com.xcenter.cabinet.model.FileModel;
import com.xcenter.cabinet.util.DateUtil;
import com.xcenter.cabinet.util.SimpleIdUtil;

@Service(FileService.ID)
public class FileServiceImpl implements FileService {
	
	@Value("${cabinet.root}")
	private String root;
	
	@Autowired
	private FileDao fileDao;
	
	@Override
	public void upload(String bucket, MultipartFile[] files) {
		String[] mds = new String[files.length];
		for (int i = 0; i < files.length; i++) {
			MultipartFile mf = files[i];
			if(mf == null) {
				continue;
			}
			mds[i] = FileUtils.getMd5(mf);
		}
		Long[] ids = SimpleIdUtil.genIds(files.length);
		// 本地存储
		String folderPath = FileUtils.genFolderPath(bucket);
		String[] filenames = null;
		try {
			filenames = FileUtils.storeFiles(root + File.separator + folderPath, ids, files);
		} catch (IllegalStateException | IOException e) {
			throw new RuntimeException("本地存储文件错误");
		}
		// 数据库存储
		List<FileModel> list = new ArrayList<>();
		FileModel model = null;
		for (int i = 0; i < files.length; i++) {
			MultipartFile mf = files[i];
			if(mf == null) {
				continue;
			}
			model = new FileModel();
			model.setId(ids[i]);
			model.setFilename(filenames[i]);
			model.setFolderPath(folderPath);
			model.setSize(mf.getSize());
			model.setUploadDate(DateUtil.getCurrTs());
			model.setMd5(mds[i]);
			model.setOrigFilename(mf.getOriginalFilename());
			list.add(model);
		}
		if(list.isEmpty()) {
			return;
		}
		fileDao.batchInsert(list);
	}

	@Override
	public FileModel queryById(Long id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public FileModel[] queryByIds(Long[] ids) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void deleteById(Long id) {
		// TODO Auto-generated method stub

	}

	@Override
	public void deleteByIds(Long[] ids) {
		// TODO Auto-generated method stub

	}

}
